package com.jf.cloud.order.controller.multishop;

import cn.hutool.core.collection.CollectionUtil;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.order.dto.OrderVirtualInfoDTO;
import com.jf.cloud.common.order.vo.OrderVO;
import com.jf.cloud.common.order.vo.OrderVirtualInfoVO;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.common.security.AuthUserContext;
import com.jf.cloud.order.model.Order;
import com.jf.cloud.order.service.OrderService;
import com.jf.cloud.order.service.OrderVirtualInfoService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController("multishopOrderVirtualInfoController")
@RequestMapping("/m/order_virtual_info")
@Tag(name = "multishop-虚拟订单接口")
public class OrderVirtualInfoController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderVirtualInfoService orderVirtualInfoService;
    @Autowired
    private MapperFacade mapperFacade;

    @GetMapping("/order_info/{orderId}")
    @Operation(summary = "根据订单号获取虚拟订单信息" , description = "根据订单号获取订单信息")
    public ServerResponseEntity<OrderVO> info(@PathVariable("orderId") Long orderId) {
        Long shopId = AuthUserContext.get().getTenantId();
        Order order = orderService.getOrderAndOrderItemData(orderId, shopId);
        OrderVO orderVO = mapperFacade.map(order, OrderVO.class);
        if(Objects.equals(order.getOrderMold(),1)){
            List<OrderVirtualInfoVO> orderVirtualInfos = orderVirtualInfoService.getByOrderIdAndStationId(orderId, null);
            if(CollectionUtil.isNotEmpty(orderVirtualInfos)){
                orderVO.setOrderVirtualInfoList(orderVirtualInfos);
            }
        }
        return ServerResponseEntity.success(orderVO);
    }

    @PutMapping("/order_write_off_by_order_id")
    @Operation(summary = "用户虚拟商品订单核销操作" , description = "用户虚拟商品订单核销操作")
    //@PreAuthorize("@pms.hasPermission('order:virtual:update')")
    public ServerResponseEntity<Boolean> orderWriteOffByOrderId(@RequestBody OrderVirtualInfoDTO orderVirtualInfoDTO) {
        Long orderId = orderVirtualInfoDTO.getOrderId();
        Long shopId = AuthUserContext.get().getTenantId();
        if (Objects.isNull(orderId)) {
            // 订单不存在
            throw new LuckException("订单不存在");
        }
        Order order = orderService.getOrderAndOrderItemData(orderId, shopId);
        if (Objects.isNull(order) || order.getOrderMold() == 0) {
            // 订单不存在
            throw new LuckException("订单不存在");
        }
        return ServerResponseEntity.success(orderVirtualInfoService.orderWriteOffByOrderId(orderVirtualInfoDTO, order, null));
    }
}
